<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { DeleteListData, GetData, PatchModifyType, PostCopyData, patchApplyCon, patchSubscribecon } from '@/api/modules/freetrial'
import GetCacheData from '@/store/modules/NewPageCache'

const imgDomain = 'https://img1.eprhan.cc'
const router = useRouter()
const cacheData = GetCacheData()
let PageNum = cacheData.GetCacheData('freetrial').currentPage

const findFrom = ref({
  ...(cacheData.GetCacheData('freetrial').fromData),
})
const dataList: any = reactive({
  list: [],
  option: [],
})
const loading = ref(true)
const total = ref(0)

async function GetDataList(PageIndex: number = 1, PageSize: number = 20) {
  const params = {
    PageIndex,
    PageSize,
    ...(findFrom.value.Title && ({ Title: findFrom.value.Title })),
    ...(findFrom.value.Enable !== '~' && ({ Enable: findFrom.value.Enable })),
    ...(findFrom.value.status !== '~' && ({ status: findFrom.value.status })),
  }
  await GetData(params).then(async (dataRes: any) => {
    if (dataRes.succeeded) {
      dataList.list = dataRes.data.items
      total.value = dataRes.data.total
      loading.value = false
    }
  })
  loading.value = false
}

// 修改状态
async function ModifyType(params: any) {
  // const params = {
  //   actDrawId: 1000100,
  //   actStatus: 1,
  // }
  await PatchModifyType(params).then((res: any) => {
    if (res.statusCode === 200) {
      ElMessage.success('修改成功')
      GetDataList(cacheData.GetCacheData('freetrial').currentPage, cacheData.GetCacheData('freetrial').currentSize)
    }
    else {
      if (typeof res.errors === 'string') {
        ElMessage.error(`修改失败。${res.errors}`)
      }
      else {
        let errorStr = ''
        for (const key in res.errors) {
          errorStr += `${key}：${res.errors[key]}；`
        }
        ElMessage.error(`修改失败。${errorStr}`)
      }
    }
  })
}

// 查询
function Inquire() {
  GetDataList(1, cacheData.GetCacheData('freetrial').currentSize)
  cacheData.SetCacheData('freetrial', PageNum, cacheData.GetCacheData('freetrial').currentSize, findFrom.value)
}

// 添加
function AddData() {
  router.push({
    name: 'freetrialDetail',
  })
}

// 编辑
function EditData(id: number) {
  router.push({
    name: 'freetrialDetail',
    query: {
      id,
    },
  })
}

function DeleteData(id: number) {
  ElMessageBox.confirm('确定删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    DeleteListData(id).then((res: any) => {
      if (res.succeeded) {
        ElMessage.success('删除成功')
        GetDataList(cacheData.GetCacheData('freetrial').currentPage, cacheData.GetCacheData('freetrial').currentSize)
      }
      else {
        ElMessage.error(`删除失败${res.errors}`)
      }
    })
  })
}

// 查看记录
function Examine(id: number) {
  router.push({
    name: 'freetrialApply',
    query: {
      TrialProductId: id,
    },
  })
}

// 修改订阅人数
function SetSubscribeCon(message: any) {
  const params = {
    id: message.row.id,
    subscribeCon: message.row.subscribeCon,
  }
  patchSubscribecon(params).then((res: any) => {
    if (res.data) {
      ElMessage.success('修改成功。')
    }
    else {
      ElMessage.error(`修改失败。${res.errors}`)
      GetDataList(cacheData.GetCacheData('freetrial').currentPage, cacheData.GetCacheData('freetrial').currentSize)
    }
  })
}

// 修改参与人数
function SetAapplyCon(message: any) {
  const params = {
    id: message.row.id,
    applyCon: message.row.applyCon,
  }
  patchApplyCon(params).then((res: any) => {
    if (res.data) {
      ElMessage.success('修改成功。')
    }
    else {
      ElMessage.error(`修改失败。${res.errors}`)
      GetDataList(cacheData.GetCacheData('freetrial').currentPage, cacheData.GetCacheData('freetrial').currentSize)
    }
  })
}

function CopyData(id: number) {
  ElMessageBox.confirm(
    '您确定要复制该商品吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      PostCopyData(id).then((res: any) => {
        if (res.succeeded) {
          ElMessage.success('复制成功。')
          GetDataList(cacheData.GetCacheData('freetrial').currentPage, cacheData.GetCacheData('freetrial').currentSize)
        }
        else {
          ElMessage.error(`复制失败。${res.errors}`)
        }
      })
    })
}

// 页码
function handleSizeChange(val: number) {
  GetDataList(1, val)
  cacheData.SetCacheData('freetrial', PageNum, val)
}
function handleCurrentChange(val: number) {
  GetDataList(val, cacheData.GetCacheData('freetrial').currentSize)
  cacheData.SetCacheData('freetrial', val, cacheData.GetCacheData('freetrial').currentSize)
  PageNum = val
}

const nowPageNum = computed(() => {
  return cacheData.GetCacheData('freetrial').currentPage || 1
})

onMounted(async () => {
  GetDataList(cacheData.GetCacheData('freetrial').currentPage, cacheData.GetCacheData('freetrial').currentSize)
})
</script>

<template>
  <div>
    <PageMain>
      <SearchBar :show-toggle="false">
        <div class="header">
          <el-form label-positio="right" label-width="auto">
            <div class="from">
              <el-form-item label="活动标题">
                <el-input v-model="findFrom.Title" style="width: 300px;" placeholder="请输入活动标题" @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="是否上架">
                <el-select v-model="findFrom.Enable" placeholder="请选择" style="width: 300px;">
                  <el-option label="全部" value="~" />
                  <el-option label="上架" :value="true" />
                  <el-option label="下架" :value="false" />
                </el-select>
              </el-form-item>
              <el-form-item label="状态">
                <el-select v-model="findFrom.status" placeholder="请选择" style="width: 300px;">
                  <el-option label="全部" value="~" />
                  <el-option label="未开始" :value="1" />
                  <el-option label="进行中" :value="2" />
                  <el-option label="已结束" :value="3" />
                </el-select>
              </el-form-item>
            </div>
          </el-form>
          <div class="text-right">
            <el-button @click="Inquire">
              查询
            </el-button>
          </div>
        </div>
      </SearchBar>
      <ElDivider border-style="dashed" />
      <div class="mb-5 text-right">
        <el-button type="success" @click="AddData">
          添加
        </el-button>
      </div>
      <el-table v-loading="loading" :data="dataList.list" stripe style="width: 100%;" border>
        <el-table-column align="center" prop="id" label="ID" width="100" />
        <el-table-column align="center" prop="productId" label="商品ID" width="100" />
        <el-table-column align="center" label="封面图" width="100">
          <template #default="scope">
            <!-- <el-avatar shape="square" :size="80" :src="imgDomain + scope.row.banner" /> -->
            <ElImage style=" width: auto;height: 60px;" :src="imgDomain + scope.row.proImg" />
          </template>
        </el-table-column>
        <el-table-column header-align="center" prop="title" label="标题" width="350" />
        <el-table-column align="center" prop="lotteryTime" label="开奖时间" width="200" />
        <el-table-column align="center" label="海报背景图" width="100">
          <template #default="scope">
            <ElImage style=" width: auto;height: 60px;" :src="imgDomain + scope.row.qrcodeBgimg" />
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" prop="limitCon" label="中奖数量" width="100" /> -->
        <el-table-column align="center" prop="subscribeCon" label="订阅人数" width="100" />
        <el-table-column align="center" prop="applyCon" label="参与人数" width="100" />
        <!-- <el-table-column align="center" prop="sort" label="排序" width="100" /> -->
        <!-- <el-table-column header-align="center" prop="buyUrl" label="商品购买地址" width="350" /> -->
        <el-table-column header-align="center" prop="shareTxt" label="分享语" width="350" />
        <el-table-column align="center" label="分享图" width="100">
          <template #default="scope">
            <ElImage style=" width: auto;height: 60px;" :src="imgDomain + scope.row.shareImg" />
          </template>
        </el-table-column>
        <el-table-column align="center" prop="startTime" label="上线时间" width="200" />
        <el-table-column align="center" prop="addTime" label="添加时间" width="200" />
        <el-table-column align="center" prop="updateTime" label="更新时间" width="200" />
        <!-- <el-table-column align="center" prop="sort" label="排序" fixed="right" width="160">
          <template #default="scope">
            <el-input v-model="scope.row.sort" style="width: 120px;">
              <template #append>
                <el-button type="primary" size="small" @click="SortModification(scope)">
                  修改
                </el-button>
              </template>
            </el-input>
          </template>
        </el-table-column> -->
        <el-table-column align="center" prop="subscribeCon" label="订阅人数" fixed="right" width="160">
          <template #default="scope">
            <el-input v-model="scope.row.subscribeCon" style="width: 120px;">
              <template #append>
                <el-button type="primary" size="small" @click="SetSubscribeCon(scope)">
                  修改
                </el-button>
              </template>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="applyCon" label="参与人数" fixed="right" width="160">
          <template #default="scope">
            <el-input v-model="scope.row.applyCon" style="width: 120px;">
              <template #append>
                <el-button type="primary" size="small" @click="SetAapplyCon(scope)">
                  修改
                </el-button>
              </template>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="是否上架" fixed="right" width="120">
          <template #default="scope">
            <el-switch
              v-model="scope.row.enable"
              @click="ModifyType({ id: scope.row.id, enable: scope.row.enable })"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" fixed="right" min-width="280">
          <template #default="scope">
            <div style="line-height: 42px;">
              <el-button type="info" @click="Examine(scope.row.id)">
                查看记录
              </el-button>
              <el-button type="success" @click="CopyData(scope.row.id)">
                复制
              </el-button>
              <el-button type="primary" @click="EditData(scope.row.id)">
                编辑
              </el-button>
              <el-button type="danger" @click="DeleteData(scope.row.id)">
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div style="height: 10px;" />
      <el-pagination
        :default-page-size="cacheData.GetCacheData('freetrial').currentSize"
        :page-sizes="[5, 10, 20, 50, 100]"
        layout="total, sizes, ->, prev, pager, next, jumper"
        :total="total"
        :default-current-page="nowPageNum"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </PageMain>
  </div>
</template>

<style scoped>
.header {
  display: grid;
  grid-template-columns: 6fr 1fr;

  .from {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    grid-gap: 20px;

    .el-form-item {
      margin-bottom: 0;
    }
  }
}
</style>
